package p.ithorns.framework.feign.common;

import feign.Response;
import feign.codec.ErrorDecoder;
import org.apache.commons.io.IOUtils;
import p.ithorns.framework.common.utils.JsonUtil;
import p.ithorns.framework.core.model.Result;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

/**
 * FeignErrorDecoder
 *
 * @author Ht.L
 * @date 2024-03-27 15:58
 * @since 1.0.0
 */
public class FeignErrorDecoder implements ErrorDecoder {

    @Override
    public Exception decode(String s, Response response) {
        Response.Body body = response.body();
        try(InputStream inputStream = body.asInputStream()) {
            String json = IOUtils.toString(inputStream, Charset.defaultCharset());
            Result<?> result = JsonUtil.fromJson(json, Result.class);
            if (null == result || !result.isSuccess()) {
                throw new BizException();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        throw new BizException("Feign error");
    }

}